package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用指定的构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class cls = Class.forName("reflect.Person");
        /*
          Constructor是反射对象之一, 表示构造器方法
         */

        //获取无参构造器
        Constructor constructor = cls.getConstructor();
        Object obj = constructor.newInstance(); //new Person();
        System.out.println(obj); //Person{name='null', age=0}
        //获取String参构造器
        Constructor constructor1 = cls.getConstructor(String.class);
        Object obj1 = constructor1.newInstance("张三"); //new Person("张三");
        System.out.println(obj1); //Person{name='张三', age=0}
        //获取String+int参构造器
        Constructor constructor2 = cls.getConstructor(String.class, int.class);
        Object obj2 = constructor2.newInstance("李四",30); //new Person("李四",30);
        System.out.println(obj2); //Person{name='李四', age=30}
    }
}
